package com.fair.concurrency.rw;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: 朝花不迟暮
 * @Date: 2021/10/28 22:36
 * @Description: 读写锁实践案例
 */
public class ReadWriteLockExample {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.put(num + "", num + "");
            }, num + "").start();
        }
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(num + "");
            }, num + "").start();
        }

    }
}

class MyCache {
    private Map<String, Object> map = new HashMap<>();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    public void put(String key, Object val) {
        rwLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "- 开始写操作");
            map.put(key, val);
            Thread.sleep(500);
            System.out.println(Thread.currentThread().getName() + "- 写完了~~");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public Object get(String key) {
        rwLock.readLock().lock();
        Object obj = null;
        try {
            System.out.println(Thread.currentThread().getName() + "- 开始读操作");
            obj = map.get(key);
            Thread.sleep(500);
            System.out.println(Thread.currentThread().getName() + "- 读完了~~");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rwLock.readLock().unlock();
        }
        return obj;
    }
}